/*
 * yauosk - Yet Another Useless Operating System Kernel
 *
 * Copyright (c) 2009-2010 Matteo Cicuttin
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 * derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <systm.h>
#include <sys/types.h>
#include <arch/machine.h>

#define	CONFIG_ADDRESS	0xCF8
#define CONFIG_DATA		0xCFC
#define PCI_MAX_BUS		256
#define PCI_MAX_DEV		32

ushort
pci_config_read(ushort bus, ushort dev, ushort func, ushort ofs)
{
	uint addr;
	
	addr = (bus << 16) | (dev << 11) | (func << 8) | (ofs & 0xfc) | 0x80000000;
	outl(CONFIG_ADDRESS, addr);
	
	return (ushort) (inl(CONFIG_DATA) >> (ofs & 2) * 8) & 0xffff;
}

void
pci_enum(void)
{
	ushort bus, dev;
	ushort vendor_id, device_id;
	
	printf("Enumerating PCI bus\n");
	
	for(bus = 0; bus < PCI_MAX_BUS; bus++)
	{
		for(dev = 0; dev < PCI_MAX_DEV; dev++)
		{
			if ( (vendor_id = pci_config_read(bus,dev,0,0)) != 0xFFFF )
			{
				device_id = pci_config_read(bus,dev,0,2);
				printf("  Bus %d, device %d: found PCI device %x:%x\n",
						bus, dev, vendor_id, device_id);
			}
		}
	}
}